﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	/// <summary>
	/// Hooks into woven assemblies - BeforeInvoke is called before method invocation (duh),
	/// and AfterInvoke is called afterwards.
	/// </summary>
	public class LogWrapper : AroundMethodBase, IAroundInvoke
	{
		protected override void Execute(IInvocationContext context, CutpointType when, object returnValue)
		{
			// The "this" object being used for the method call
			object thisObject = context.Target;

			// Get the "Logable" attributes attach to the method being called
			LogableAttribute[] attrs = context.TargetMethod.ReadAttribute<LogableAttribute>();

			attrs.ForEachAttribute(delegate(LogableAttribute attr)
			{
				// If before method execution, log the specified "before" message
				// The log message can use {0}...{n} to write out the method's parameter values
				if (when == CutpointType.Before && !string.IsNullOrEmpty(attr.MessageType))
				{
					GlobalLogger.Log(attr.MessageType, String.Format(attr.LogMessage, context.Arguments), attr.LogLevel);
				}
				// If after method execution, log the specified "after" message.
				// The log message can use {0} to write out the method's return value
				else if (when == CutpointType.After && !string.IsNullOrEmpty(attr.MessageTypeAfter))
				{
					GlobalLogger.Log(attr.MessageTypeAfter, String.Format(attr.LogMessageAfter, returnValue), attr.LogLevelAfter);
				}
			});
		}
	}
}

